<template>
  <view class="register-page">
    <view class="bg">
      <image src="../../static/login_bg.jpeg"></image>
    </view>

    <view class="wrapper">
      <view class="header">
        <text class="title">用户注册</text>
      </view>

      <uni-forms ref="form" class="form" :modelValue="formData" :rules="rules">
        <uni-forms-item name="phone_num" required>
          <uni-easyinput v-model="formData.phone_num" placeholder="请输入手机号" type="number" prefix-icon="phone" />
        </uni-forms-item>

        <uni-forms-item name="password" required>
          <uni-easyinput
            v-model="formData.password"
            placeholder="请输入密码（8-16位）"
            type="password"
            prefix-icon="locked"
          />
        </uni-forms-item>

        <uni-forms-item name="confirm_password" required>
          <view :class="checkPwd ? 'confirm_password_red' : ''">
            <uni-easyinput
              v-model="formData.confirm_password"
              placeholder="请输入确认密码"
              type="password"
              prefix-icon="locked"
              @input="handleInput()"
            />
          </view>
        </uni-forms-item>
        <!-- 
        <uni-forms-item name="code" required>
          <uni-easyinput v-model="formData.code" placeholder="请输入验证码" type="number" prefix-icon="email">
            <template v-slot:right>
              <text class="code-btn" @click="getSmsCode">
                {{ codeText }}
              </text>
            </template>
          </uni-easyinput>
        </uni-forms-item> -->

        <button class="register-btn" @click="handleRegister">立即注册</button>
      </uni-forms>
    </view>
  </view>
</template>

<script>
import aesEncrypt from '../../utils/encrypt'
export default {
  data() {
    return {
      formData: {
        phone_num: '',
        sms_code: '',
        password: '',
        confirm_password: '',
        avatar: '',
        username: ''
      },
      codeText: '获取验证码',
      countdown: 60,
      checkPwd: false,
      aa: null,
      rules: {
        password: {
          // name 字段的校验规则
          rules: [
            // 校验 name 不能为空
            {
              required: true,
              errorMessage: '请输入密码'
            },
            // 对name字段进行长度验证
            {
              minLength: 8,
              maxLength: 16,
              errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符'
            }
          ],
          // 当前表单域的字段中文名，可不填写
          label: '密码',
          validateTrigger: 'submit'
        },
        confirm_password: {
          // name 字段的校验规则
          rules: [
            // 校验 name 不能为空
            {
              required: true,
              errorMessage: '请输入确认密码'
            },
            // 对name字段进行长度验证
            {
              minLength: 8,
              maxLength: 16,
              errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符'
            }
          ],
          // 当前表单域的字段中文名，可不填写
          label: '确认密码',
          validateTrigger: 'submit'
        },
        phone_num: {
          rules: [
            {
              required: true,
              errorMessage: '请输入手机号'
            },
            {
              format: 'number',
              errorMessage: '请输入合法的手机号'
            },
            {
              pattern: '^(?:\\+?86)?1(?:3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[134578]|8[0-9]|9[0-35-9])\\d{8}$',
              errorMessage: '请输入合法的手机号'
            }
          ],
          // 当前表单域的字段中文名，可不填写
          label: '手机号',
          validateTrigger: 'submit'
        },

        code: {
          rules: [
            {
              required: true,
              errorMessage: '请输入短信验证码'
            },
            {
              minLength: 6,
              maxLength: 6,
              errorMessage: '{label}长度为{minLength}个字符'
            }
          ],

          label: '短信验证码',
          validateTrigger: 'submit'
        }
      }
    }
  },

  async onLoad() {},

  methods: {
    async getSmsCode() {
      if (this.countdown !== 60) return

      const { data: res } = await uni.request({
        url: this.$domain.data + '/sendSMSCode'
      })

      // console.log(res)
      if (res.status != 200) {
        this.$checkStatus(res.status)
        return
      }

      uni.showToast({
        icon: 'none',
        title: res.message,
        delay: 5000
      })

      // 调用短信接口
      this.timer = setInterval(() => {
        if (this.countdown <= 0) {
          clearInterval(this.timer)
          this.codeText = '重新获取'
          this.countdown = 60
          return
        }
        this.codeText = `${this.countdown--}秒后重试`
      }, 1000)
    },

    async handleRegister() {
      this.$refs.form.validate(async (valid) => {
        if (valid != null) {
          return
        }

        if (this.checkPwd) {
          uni.showToast({
            icon: 'none',
            title: '两次密码不相同'
          })
          return
        }

        uni.showLoading({ title: '注册中...' })
        // 调用注册接口

        // 获取密钥，过期后重新拿
        if (this.aa == null || this.aa.et < new Date().getTime()) {
          const a = await uni.request({
            method: 'GET',
            url: this.$domain.data + '/userRegLogin'
          })

          if (a.data.status != 200) {
            this.$checkStatus(res.status)
            this.aa = null
            return
          }
          this.aa = JSON.parse(a.data.data)
          this.aa.id = this.getExId(a.data.data)
        }

        // 判断form

        // 加密
        const formData = this.formData
        const pwd = aesEncrypt(formData.password, this.aa.a.s, this.aa.a.iv)
        const c_pwd = aesEncrypt(formData.confirm_password, this.aa.a.s, this.aa.a.iv)

        const phone_num = formData.phone_num
        const sms_code = formData.sms_code

        const { data: res } = await uni.request({
          url: `${this.$domain.data}/regUser`,
          header: getApp().globalData.header,
          method: 'POST',
          data: {
            phone_num: phone_num,
            password: pwd,
            confirm_password: c_pwd,
            a_id: this.aa.id,
            sms_code: sms_code
          }
        })

        uni.hideLoading()
        if (res.status !== 200) {
          this.$checkStatus(res.status, '注册失败，请重试')
          return
        }

        uni.showToast({
          icon: 'success',
          title: '注册成功'
        })

        setTimeout(() => {
          uni.navigateBack()
        }, 500)
      })
    },

    handleInput(e) {
      if (e != this.formData.password) {
        this.checkPwd = true
      } else {
        this.checkPwd = false
      }
    },

    getExId(jsonStr) {
      const arr = jsonStr.split(',')
      const ids = arr[arr.length - 1]
      const id = ids.split('}')[0].split(':')[1] + ''

      return id
    }
  }
}
</script>

<style lang="scss">
.confirm_password_red {
  border-radius: 4px;
  box-shadow: 0upx 0upx 5upx red;
}

.register-page {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .bg {
    z-index: -1;
    position: absolute;
    top: 0%;
    left: 0%;
    width: 100vw;
    height: 100vh;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .wrapper {
    width: 670upx;
    padding: 30upx 40upx;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 20upx;
    position: relative;
    box-sizing: border-box;
  }

  .header {
    text-align: center;
    margin-bottom: 80upx;

    .logo {
      width: 160upx;
      height: 160upx;
      margin-bottom: 30upx;
    }

    .title {
      font-size: 48upx;
      font-weight: bold;
      display: block;
    }
  }

  .login-btn {
    background: #007aff;
    color: #fff;
    height: 90upx;
    line-height: 90upx;
    border-radius: 45upx;
    font-size: 34upx;
    margin-top: 60upx;
  }

  .register-link {
    text-align: center;
    margin-top: 40upx;
    color: #666;

    text {
      color: #007aff;
      margin-left: 10upx;
    }
  }

  .code-btn {
    color: #007aff;
    font-size: 28upx;
    padding: 0 20upx;
  }
}
</style>
